<template>
<div class="editMail">
  <el-form :inline="true" ref="mailForm" :rules="rules" :model="mailForm" >
    <el-form-item label="内容性质：">
      <el-select v-model="mailForm.attrId" placeholder="">
        <el-option v-for="item,n in attrs" :value="item.id" :label="item.name" :key="n.toString()"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item class="block-line">
      <h3>发送内容</h3>
      <el-col :span="7">
        <div class="getMailView">
          <el-form-item label="邮件名称" class="mail-fl" prop="title">
            <el-input v-model="mailForm.title" placeholder="请输入邮件名称"></el-input>
          </el-form-item>
          <el-form-item label="发件人" class="mail-fl" prop="">
            <el-input v-model="curMailplt.sender" disabled placeholder="只能使用英文字母和数字"></el-input>
          </el-form-item>
          <el-form-item label="@" class="mail-fl" prop="">
            <el-select v-model="curMailplt.sendTypeSel" disabled placeholder="">
              <el-option v-for="item,n in curMailplt.sendType" :value="item.value" :label="item.label" :key="n.toString()"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发件人显示名" class="mail-fl" prop="">
            <el-input v-model="curMailplt.sendShow" disabled placeholder=""></el-input>
          </el-form-item>
          <p class="sender-view-tip">发件人预览</p>
          <p class="sender-view-cont">{{curMailplt.sendView}}</p>
        </div>
      </el-col>
      <el-col :span="17">
        <div class="send-wrap cl">
          <mail-editor ref="editor"
          :content.sync="mailForm.content"
          @contentChange="handleEditorChange">
          </mail-editor>
        </div>
      </el-col>
      <el-col :span="24" class="btn-wrap">
        <el-button class="chooseBtn" @click="dialogChooseMailHad">选择已有</el-button>
        <el-button class="chooseBtn" @click="testSendPup">测试发送</el-button>
      </el-col>
    </el-form-item>
    <el-form-item label="" class="block-line business-wrap">
      <el-checkbox v-model="mailForm.groupType">上传到事业部内容库<em>（直接上传，不审核）</em></el-checkbox>
      <!-- <el-form-item label="" class="block-line appoint-wrap">
        <el-checkbox v-show="mailForm.groupType" v-model="checkedAppoint">指定用户可见<em>（只有指定用户可见，不审核）</em></el-checkbox>
        <div v-show="checkedAppoint" class="appoint-detail"><span>已选 10</span><a href="javascript:;">查看详情</a></div>
      </el-form-item> -->
    </el-form-item>
    <el-form-item v-if="showCommonType" label="" class="block-line">
      <el-checkbox v-model="mailForm.commonType">上传到公共内容库<em>（将提交品牌VI审核）</em></el-checkbox>
    </el-form-item>
  </el-form>
  <el-row class="submit-wrap">
    <el-col :span="24">
      <el-button type="primary" style="width:100px" :loading="isSaving" @click="submitForm('mailForm')">{{mailForm.save?'保存':'返回'}}</el-button>
      <el-button v-if="!mailForm.save" type="primary" :loading="isSaving" style="width:100px" @click="otherSubmitForm('mailForm')">另存为</el-button>
      <el-button type="primary" v-if="mailForm.save" :loading="isSaving" style="width:100px" @click="submitForm('mailForm')">保存并发送</el-button>
    </el-col>
  </el-row>
  <el-dialog
    title="测试发送"
    :visible.sync="dialogTestSend">
    <el-form :inline="true" ref="testForm" :rules="rules" :model="testForm" class="test-wrap">
      <el-form-item label="测试邮箱" prop="target">
        <el-input v-model="testForm.target" placeholder="请输入邮箱" class="test-phone"></el-input>
      </el-form-item>
      <el-form-item label="验证码" class="vcode-wrap" prop="captcheCode">
        <el-input v-model="testForm.captcheCode" placeholder="请输入验证码" class="test-vcode"></el-input>
        <img class="captchaImg" :src="captchaImg" alt="验证码" @click="getCaptchaImg">
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="testSendSubmit('testForm')">确 定</el-button>
    </span>
  </el-dialog>
  <el-dialog
    title="选择邮件模板"
    :visible.sync="mailForm.dialogChooseMail">
    <mail-choose-had ref="mailChoose" :mailList="mailList" :mailListForm="mailListForm" :mailForm="mailForm" v-on:refreshbizlines="getMailList" v-on:usecontent="contentChangeEditor"></mail-choose-had>
  </el-dialog>
  <new-send :show.sync="dialogNewSend" :newSendData.sync="newSendItem" ref="sendset"></new-send>
</div>
</template>
<script>
  import {mapActions, mapState} from 'vuex'
  import mailChooseHad from '@/components/common/content/mailChooseHad'
  import mailEditor from '@/components/common/content/mailEditor'
  import newSend from '@/components/common/content/newSend'
  export default {
    data () {
      return {
        mailForm: {
          id: this.$route.params.id === 'add' ? '' : this.$route.params.id,
          attrId: '',
          title: '',
          content: '',
          attachName: '',
          attachPath: '',
          groupType: true,
          commonType: false,
          dialogChooseMail: false,
          save: true
        },
        testForm: {
          type: 4,
          captchaKey: '',
          target: '',
          testTitle: '',
          testContent: '',
          captcheCode: ''
        },
        mailListForm: {
          title: '',
          page: 1,
          size: 10
        },
        curMailplt: {
          sender: '',
          sendType: [],
          sendTypeSel: '',
          sendShow: '',
          sendView: ''
        },
        captchaImg: '',
        checkedAppoint: false,
        dialogTestSend: false,
        clickFlag: false,
        showCommonType: true,
        dialogNewSend: false,
        newSendItem: {
          title: '',
          id: '',
          type: 4
        },
        isSaving: false,
        rules: {
          title: {required: true, message: '请输入邮件名称', trigger: 'blur'},
          content: {required: true, message: '请输入短信内容', trigger: 'blur'},
          target: [{required: true, message: '请输入邮箱', trigger: 'blur'},
            {pattern: /^([0-9A-Za-z-_.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/, message: '请输入正确的邮箱', trigger: 'blur'}],
          captcheCode: {required: true, message: '请输入验证码', trigger: 'blur'}
        }
      }
    },
    components: {
      mailChooseHad, mailEditor, newSend
    },
    mounted () {
      this.initPage()
    },
    computed: {
      ...mapState({
        mailList: state => state.contentManage.mailNewsList,
        mailDetail: state => state.contentManage.mailDetail,
        attrs: state => state.contentManage.contentType
      })
    },
    methods: {
      ...mapActions(['getMailNewsList', 'editMail', 'getMailDetail', 'getCurMailplt', 'getCaptcha', 'testSend', 'getContentTypes']),
      initPage () {
        if (!this.mailForm.id && this.$route.params.mailId !== 'self') {
          this.mailForm.id = this.$route.params.mailId
        }
        this.mailForm.id && this.getDetailData(this.mailForm.id)
        this.getContentTypes().then(() => {
          this.mailForm.attrId = this.attrs[0].id
        })
        this.getCurMailplt().then((res) => {
          let dat = res.data.data
          if (res.data.code === 1) {
            this.curMailplt.sendShow = dat.nickName
            this.curMailplt.sender = dat.account.split('@')[0]
            this.curMailplt.sendType = [{label: dat.account.split('@')[1], value: dat.account.split('@')[1]}]
            this.curMailplt.sendTypeSel = dat.account.split('@')[1]
            this.curMailplt.sendView = dat.account
          }
        })
      },
      getCaptchaImg () {
        this.getCaptcha().then(res => {
          if (res.data.code === 1) {
            this.captchaImg = 'data:image/png;base64,' + res.data.data.base64Image
            this.testForm.captchaKey = res.data.data.key
          }
        })
      },
      getMailList () {
        this.getMailNewsList({...this.mailListForm})
      },
      dialogChooseMailHad () {
        this.mailForm.dialogChooseMail = true
        this.getMailList()
      },
      // 日期格式化
      dateFormat (date) {
        return this.$date.format(new Date(date), 'YYYY-MM-DD hh:mm:ss')
      },
      // 编辑器内容改变
      handleEditorChange (content) {
        // this.mailForm.content = content
        return content
      },
      // 获取详情数据
      getDetailData (id) {
        this.getMailDetail(id)
          .then(() => {
            this.mailForm = {
              ...this.mailForm,
              ...this.mailDetail
            }
            this.mailForm.groupType = Boolean(this.mailForm.groupType)
            this.mailForm.commonType = Boolean(this.mailForm.commonType)
            this.showCommonType = !this.mailDetail.commonType
          })
      },
      contentChangeEditor (obj) {
        this.getDetailData(obj.id)
        // this.$refs.editor.setContent(cont)
      },
      // 保存提交数据
      submitForm (form) {
        if (this.mailForm.save) {
          this.mailForm.commonType = Number(this.mailForm.commonType)
          this.submitData(form)
        } else {
          this.$router.go(-1)
        }
      },
      // 另存为
      otherSubmitForm (form) {
        this.mailForm.id = null
        this.mailForm.commonType = 0 // Number(this.mailForm.commonType)
        this.submitData(form)
      },
      // 提交数据
      submitData (form) {
        this.mailForm.groupType = Number(this.mailForm.groupType)
        this.mailForm.content = this.$refs.editor.getEditorCont()
        if (this.mailForm.content === '') {
          this.$message({
            type: 'warning',
            message: '请输入邮件内容'
          })
          return
        }
        this.mailForm.createTime = null
        if (this.$route.params.mailId !== 'self') {
          this.mailForm.id = null
        }
        this.$refs[form].validate(valid => {
          if (valid) {
            this.isSaving = true
            this.editMail(this.mailForm)
              .then(res => {
                this.isSaving = false
                if (res.data.code === 1) {
                  this.mailForm.id = res.data.data
                  this.saveAndSend(this.mailForm.id, this.mailForm.title)
                  this.$message({
                    type: 'success',
                    message: '提交成功'
                  })
                }
              })
          }
        })
      },
      // 发送设置
      saveAndSend (id, title) {
        this.dialogNewSend = true
        this.newSendItem.title = title
        this.newSendItem.id = id
        this.$refs.sendset.getSendRecord(id)
      },
      // 点击测试发送
      testSendPup () {
        this.dialogTestSend = true
        this.getCaptchaImg()
      },
      // 测试发送提交
      testSendSubmit (form) {
        this.testForm.testTitle = this.mailForm.title
        this.testForm.testContent = this.$refs.editor.getEditorCont()
        if (this.testForm.testTitle === '') {
          this.$message({
            type: 'warning',
            message: '请输入邮件名称'
          })
          this.dialogTestSend = false
          return
        }
        if (this.testForm.testContent === '') {
          this.$message({
            type: 'warning',
            message: '请输入邮件内容'
          })
          this.dialogTestSend = false
          return
        }
        this.$refs[form].validate(valid => {
          if (valid) {
            this.testSend(this.testForm)
              .then(res => {
                if (res.data.code === 1) {
                  this.$message({
                    type: 'success',
                    message: '发送成功'
                  })
                  this.dialogTestSend = false
                } else if (res.data.code === 3) {
                  this.getCaptchaImg()
                }
              })
          }
        })
      }
    }
  }
</script>
<style lang="scss">
  .vb-h{
    visibility: hidden;
  }
  .editMail{
    .block-line{display:block;width:100%;}
    .block-line .el-form-item__content{display: block;}
  }
  .getMailView{
    background: #eff2f7;
    text-align: left;
    padding: 15px 30px 30px;
    min-height: 441px;
    .mail-fl, .el-select{
      width: 100%;
    }
    p{
      text-align: left;
      line-height: 1.6;
    }
    .view-box{
      margin-top: 20px;
      display: inline-block;
      position: relative;
    }
    .sender-view{
      &-tip{
        line-height: 36px;
      }
    }
  }
  .btn-wrap{
    margin-top: 10px;
  }
  .send-wrap .mail-fl{
    .el-form-item__label, .el-form-item__content{float: left;}
  }
  .chooseBtn{
    background: #f9fafc;
    margin-left: 15px;
  }
  .sign-wrap{
    margin: 20px 0;
    .el-select{
      width: 169px;
    }
  }
  .cont-wrap{
    margin-top: 20px;
    .cont-top{
      padding: 5px 15px;
      background: #f9fafc;
      border-bottom: 1px solid #ccc;
      .el-button{
        padding: 7px;
        color: #666;
        min-width: 126px;
      }
    }
    .el-textarea__inner{
      border: none;
      resize: none;
    }
  }
  .business-wrap{
    padding-top: 10px;
    border-top: 1px solid #ccc;
    margin-bottom: 10px;
  }
  .el-checkbox__label em{
    color: #ccc;
  }
  .appoint-wrap{
    margin-left: 25px;
    .appoint-detail{
      margin-left: 25px;
      a{
        margin-left: 25px;
        text-decoration: none;
      }
    }
  }
  .submit-wrap{
    padding: 20px 0;
    border-top: 1px solid #ccc;
    text-align: center;
  }

  .test-wrap{
    .el-form-item{width: 100%;}
    .el-form-item__label{min-width: 92px;text-align: right;}
  }
  .test-phone input{width: 260px;}
  .test-vcode{width: 160px;}
  .captchaImg{
    height: 36px;
  }
</style>
